#!/bin/bash

# Linux specific paths
HTML_DIR="/usr/local/nginx/html"
CONFIG_DIR="/usr/local/nginx/conf/"
NGINX_CONF="nginx_linux.conf"
CERT_DIR="/root/cert"

# Set error handling
set -e

# Logging function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# Check if required directories exist
if [ ! -d "$HTML_DIR" ]; then
    log "Creating HTML directory: $HTML_DIR"
    mkdir -p "$HTML_DIR"
fi

if [ ! -d "$CONFIG_DIR" ]; then
    log "Error: Nginx config directory does not exist: $CONFIG_DIR"
    exit 1
fi

# Create cert directory if it doesn't exist
if [ ! -d "$CERT_DIR" ]; then
    log "Creating SSL certificate directory: $CERT_DIR"
    mkdir -p "$CERT_DIR"
fi

log "Updating HTML files"
# Clear existing HTML files
rm -rf "$HTML_DIR"/*

# Extract html.war if it exists
if [ -f "html.war" ]; then
    log "Extracting html.war to $HTML_DIR"
    unzip -oq html.war -d "$HTML_DIR"
else
    # Copy html directory directly if html.war doesn't exist
    if [ -d "../html" ]; then
        log "Copying html directory directly"
        cp -r ../html/* "$HTML_DIR/"
    else
        log "Error: Neither html.war nor ../html directory found"
        exit 1
    fi
fi

# Rename helloWorld.html to index.html if it exists
if [ -f "$HTML_DIR/module/index/helloWorld.html" ]; then
    log "Renaming helloWorld.html to index.html"
    mv "$HTML_DIR/module/index/helloWorld.html" "$HTML_DIR/index.html"
    log "index.html replaced with helloWorld.html content"
else
    log "helloWorld.html not found, skipping rename"
fi

# Update nginx configuration
log "Updating nginx configuration"
if [ -f "$NGINX_CONF" ]; then
    cp -f "$NGINX_CONF" "$CONFIG_DIR/nginx.conf"
    
    # Copy SSL certificates if they exist in the current directory
    if [ -f "yamhk.top.cer" ] && [ -f "yamhk.top.key" ]; then
        log "Copying SSL certificates to $CERT_DIR"
        cp -f "yamhk.top.cer" "$CERT_DIR/"
        cp -f "yamhk.top.key" "$CERT_DIR/"
    else
        log "Warning: SSL certificates not found in current directory, skipping copy"
    fi
else
    log "Warning: Nginx config file $NGINX_CONF not found"
fi

# Reload nginx
log "Reloading nginx"
if [ -f "/usr/local/nginx/sbin/nginx" ]; then
    cd "/usr/local/nginx/sbin" && ./nginx -s reload
elif command -v nginx >/dev/null 2>&1; then
    nginx -s reload
else
    log "Error: Nginx executable not found"
    exit 1
fi

# Pause for 5 seconds to let user see the output
log "Deployment completed. Pausing for 5 seconds..."
sleep 5